package com.eqdd.yiqidian.ui.mine.qiye;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.yiqidian.QiyeAuActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.AreaBean;
import com.eqdd.yiqidian.bean.EditBean;
import com.eqdd.yiqidian.bean.choose.HangyeBean;
import com.eqdd.yiqidian.bean.rebuild.OptionBean;
import com.eqdd.yiqidian.bean.utils.MultiChooseBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.IndustryTypeListActivity;
import com.eqdd.yiqidian.ui.base.BaseMultiEditActivity;
import com.eqdd.yiqidian.utils.FileUtil;
import com.eqdd.yiqidian.utils.MultiChooseTestUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.utils.SingleChooseUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.EditDialogFragment;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.ISelectAble;
import io.reactivex.Flowable;
import rx.schedulers.Schedulers;

/**
 * Created by lvzhihao on 17-4-21.
 */

public class QiyeAuActivity extends BaseMultiEditActivity {
    String imagePathIDCardFront;
    String imagePathIDCardBehand;
    String imagePathIDCardWith;
    String imagePathQiyedaima;
    String imagePathYingyezhizhao;
    String imagePathShenchanxuke;
    private String[] titles = new String[]{
            "法定代表人/企业负责人身份证正面照片上传",
            "法定代表人/企业负责人身份证反面照片上传",
            "法定代表人/企业负责人手持身份证照片",
            "企业《组织机构代码证》号码",
            "企业《组织机构代码证》拍照上传",
            "企业《营业执照》代码",
            "《营业执照》拍照上传",
            "企业《生产许可证》代码(选填)",
            "企业《生产许可证》拍照上传(选填)",
            "主要客户群体",
            "注册资本",
            "经营范围",
            "公司成立日期",
            "营业期限",
            "主营行业",
            "主要经营地点",
            "地址导航",
            "员工人数",
    };
    private String[] titleTexts = new String[]{
            "法定代表人/企业负责人身份证正面照片上传",
            "法定代表人/企业负责人身份证反面照片上传",
            "法定代表人/企业负责人手持身份证照片",
            "企业《组织机构代码证》号码",
            "企业《组织机构代码证》拍照上传",
            "企业《营业执照》代码",
            "《营业执照》拍照上传",
            "企业《生产许可证》代码(选填)",
            "企业《生产许可证》拍照上传(选填)",
            "主要客户群体",
            "注册资本",
            "经营范围",
            "公司成立日期",
            "营业期限",
            "主营行业",
            "主要经营地点",
            "地址导航",
            "员工人数",
    };
    private String[] tipTexts = new String[]{
            "法定代表人/企业负责人身份证正面照片上传",
            "法定代表人/企业负责人身份证反面照片上传",
            "法定代表人/企业负责人手持身份证照片",
            "企业《组织机构代码证》号码",
            "企业《组织机构代码证》拍照上传",
            "企业《营业执照》代码",
            "《营业执照》拍照上传",
            "企业《生产许可证》代码(选填)",
            "企业《生产许可证》拍照上传(选填)",
            "主要客户群体",
            "注册资本",
            "经营范围",
            "公司成立日期",
            "营业期限",
            "主营行业",
            "主要经营地点",
            "地址导航",
            "员工人数",
    };
    private int[] types = new int[]{
            4, 4, 4, 0, 4, 0, 4, 0, 4, 0, 0, 0, 2, 0, 4, 4, 0, 4
    };
    private QiyeAuActivityCustom dataBinding;
    private Bundle bundle;
    private List<HangyeBean> hangyeBean;
    private BottomDialog hangyeDialog;
    private BottomDialog areaDialog;
    private List<AreaBean> areaBean;
    private ActionSheetDialog numDialog;
    private String result;
    private int choosed;


    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_qiye_au);
        initTopTitleBar(View.VISIBLE, "企业认证");
        initTopRightText("认证", (v) -> {
            if (checkParams()) {
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.COM_AUTHEN)
                        .params("comid", user.getCompanyId())
                        .params("userGuid", user.getGuid())
                        .params("user", user.getUname())
                        .params("codecertifi", editBeans.get(3).getContent())
                        .params("buslicense", editBeans.get(5).getContent())
                        .params("productcertifi", editBeans.get(7).getContent())
                        .params("maincustomer", editBeans.get(9).getContent())
                        .params("registered", editBeans.get(10).getContent())
                        .params("busScope", editBeans.get(11).getContent())
                        .params("busSetdate", editBeans.get(12).getContent())
                        .params("busterm", editBeans.get(13).getContent())
                        .params("mainbus", editBeans.get(14).getContent())
                        .params("mainbusadress", editBeans.get(15).getContent())
                        .params("staffnum", editBeans.get(17).getContent())
                        .params("file1", new File(imagePathIDCardFront))
                        .params("file2", new File(imagePathIDCardBehand))
                        .params("file3", new File(imagePathIDCardWith))
                        .params("file4", new File(imagePathQiyedaima))
                        .params("file5", new File(imagePathYingyezhizhao))
                        .params("file6", new File(imagePathShenchanxuke))
                        .execute(new DialogCallBack<HttpResult>(this) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult httpResult = response.body();
                                ToastUtil.showShort(httpResult.getMsg());
                                if (httpResult.getStatus() == 200) {
                                    clearData();
                                    Schedulers.io().createWorker().schedule(() -> {
                                        FileUtil.cleanCacheImage();
                                    });
                                    isSaveData = false;
                                    finish();
                                }
                            }
                        });
            } else {
                ToastUtil.showLong("信息不完整");
            }
        });
    }

    private boolean checkParams() {
        for (int i = 0; i < quickAdapter.getData().size(); i++) {
            if (i == 7 || i == 8) {
                continue;
            }
            if (TextUtils.isEmpty(quickAdapter.getItem(i).getContent())) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void initData() {
        for (int i = 0; i < titles.length; i++) {
            EditBean editBean = new EditBean();
            editBean.setTitle(titles[i]);
            editBean.setType(types[i]);
            editBean.setContent("");
            editBean.setTextTip(tipTexts[i]);
            editBean.setTextTitle(titleTexts[i]);
            editBeans.add(editBean);
            if (i == 16) {
                editBean.setContent("定位地址");
            }
        }
        getHttpData();
    }

    @Override
    protected RecyclerView initRecyclerView() {
        return dataBinding.recyclerView;
    }

    @Override
    public void itemClick(int p) {
        switch (p) {
            case 0:
            case 1:
            case 2:
            case 4:
            case 6:
            case 8:
                choosed = p;
                PicUtil.single(this, true);
                break;
            case 14:
                Intent intent = new Intent(QiyeAuActivity.this, IndustryTypeListActivity.class);
                intent.putExtra(Config.TYPE, 2);
                intent.putExtra(Config.TITLE, "工作行业");
                startActivityForResult(intent, 14);
                break;
            case 15:
                areaDialog.show();
                break;
            case 17:
                if (numDialog == null) {
                    SingleChooseUtil.getChooseDialog(this, 4, sheetDialog -> {
                        numDialog = sheetDialog;
                        numDialog.show();
                    }, (position, strings) -> {
                        quickAdapter.getItem(17).setContent(strings.get(position - 1));
                        quickAdapter.notifyItemChanged(17);
                    });
                } else {
                    numDialog.show();
                }
                break;
        }
    }

    private void getHttpData() {
        showLoading();
        Flowable<List<AreaBean>> areaFlow = OkGo.<List<AreaBean>>get(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                .params("type", 0)
//                .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "0")
//                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .converter(new JsonConverter<List<AreaBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<List<AreaBean>>());
        Flowable<List<HangyeBean>> hangyeFlow = OkGo.<List<HangyeBean>>get(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                .params("type", 2)
//                .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "2")
//                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .converter(new JsonConverter<List<HangyeBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<List<HangyeBean>>());

        Flowable.combineLatest(areaFlow, hangyeFlow, (s, s2) -> {
                    areaBean = s;
                    hangyeBean = s2;
                    return 1;
                }
        ).subscribe(o -> {
                    initHangyePicker();
                    initAreaPicker();
                }
                , e -> {
                    hideLoading();
                    System.out.println(e.toString());
                    ToastUtil.showShort(Config.SERVER_ERROR);
                }, () -> {
                    hideLoading();
                });
    }

    private void initHangyePicker() {
        int hangyePosition = 14;

        List<MultiChooseBean> multiChooseBeen = new ArrayList<>();
        multiChooseBeen.addAll(hangyeBean);
        hangyeDialog = new MultiChooseTestUtil().getAreaDialog(QiyeAuActivity.this, 3, multiChooseBeen, (d, a) -> {
            hangyeDialog.dismiss();
            String result = "";
            for (ISelectAble iSelectAble : a) {
                result += iSelectAble.getName();
            }
            editBeans.get(hangyePosition).setContent(a.get(2).getName() + "-" + ((HangyeBean) (a.get(2).getArg())).getCode());
            quickAdapter.notifyItemChanged(hangyePosition);

        });
    }

    private void initAreaPicker() {
        int areaPosition = 15;
        List<MultiChooseBean> multiChooseBeen = new ArrayList<>();
        multiChooseBeen.addAll(areaBean);
        areaDialog = new MultiChooseTestUtil().getAreaDialog(QiyeAuActivity.this, 3, multiChooseBeen, (d, a) -> {
            areaDialog.dismiss();
            result = "";
            for (ISelectAble iSelectAble : a) {
                result += iSelectAble.getName();
            }
            editBeans.get(areaPosition).setContent(result);
            quickAdapter.notifyItemChanged(areaPosition);
            EditDialogFragment editDiglog = ChooseAlertView.getEditDiglog("请输入详细地址", "详细地址", null, contents -> {
                editBeans.get(areaPosition).setContent(result + contents.get(0));
                quickAdapter.notifyItemChanged(areaPosition);
            });
            editDiglog.show(getSupportFragmentManager(), "edit");

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.IMAGE_PATH_ID_CARD_FRONT:
                    imagePathIDCardFront = data.getStringExtra(Config.IMAGE_PATH);
                    editBeans.get(0).setContent("已选择");
                    quickAdapter.notifyItemChanged(0);
                    break;
                case Config.IMAGE_PATH_ID_CARD_BEHAND:
                    imagePathIDCardBehand = data.getStringExtra(Config.IMAGE_PATH);
                    editBeans.get(1).setContent("已选择");
                    quickAdapter.notifyItemChanged(1);
                    break;
                case Config.IMAGE_PATH_ID_CARD_WITH:
                    imagePathIDCardWith = data.getStringExtra(Config.IMAGE_PATH);
                    editBeans.get(2).setContent("已选择");
                    quickAdapter.notifyItemChanged(2);
                    break;
                case Config.IMAGE_PATH_QIYEDAIMA:
                    imagePathQiyedaima = data.getStringExtra(Config.IMAGE_PATH);
                    editBeans.get(4).setContent("已选择");
                    quickAdapter.notifyItemChanged(4);
                    break;
                case Config.IMAGE_PATH_YINGYEZHIZHAO:
                    imagePathYingyezhizhao = data.getStringExtra(Config.IMAGE_PATH);
                    editBeans.get(6).setContent("已选择");
                    quickAdapter.notifyItemChanged(6);
                    break;
                case Config.IMAGE_PATH_SHENCHANXUKE:
                    imagePathShenchanxuke = data.getStringExtra(Config.IMAGE_PATH);
                    editBeans.get(8).setContent("已选择");
                    quickAdapter.notifyItemChanged(8);
                    break;
            }
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    switch (choosed) {
                        case 0:
                            imagePathIDCardFront = PictureSelector.obtainMultipleResult(data).get(0).getCompressPath();
                            break;
                        case 1:
                            imagePathIDCardBehand = PictureSelector.obtainMultipleResult(data).get(0).getCompressPath();
                            break;
                        case 2:
                            imagePathIDCardWith = PictureSelector.obtainMultipleResult(data).get(0).getCompressPath();

                            break;
                        case 4:
                            imagePathQiyedaima = PictureSelector.obtainMultipleResult(data).get(0).getCompressPath();
                            break;
                        case 6:
                            imagePathYingyezhizhao = PictureSelector.obtainMultipleResult(data).get(0).getCompressPath();
                            break;
                        case 8:
                            imagePathShenchanxuke = PictureSelector.obtainMultipleResult(data).get(0).getCompressPath();
                            break;

                    }
                    quickAdapter.getItem(choosed).setContent("已选择");
                    quickAdapter.notifyItemChanged(choosed);
                    break;
            }
        }
        if (resultCode == RESULT_OK && requestCode == 14) {
            OptionBean bean = (OptionBean) data.getSerializableExtra("data");
            editBeans.get(14).setContent(bean.getName());
            quickAdapter.notifyItemChanged(14);
        }
    }


    @Override
    public void saveData() {
        super.saveData();
        if (!TextUtils.isEmpty(imagePathIDCardBehand)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardBehand", imagePathIDCardBehand);
        }
        if (!TextUtils.isEmpty(imagePathIDCardFront)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardFront", imagePathIDCardFront);
        }
        if (!TextUtils.isEmpty(imagePathIDCardWith)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardWith", imagePathIDCardWith);
        }
        if (!TextUtils.isEmpty(imagePathQiyedaima)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathQiyedaima", imagePathQiyedaima);
        }
        if (!TextUtils.isEmpty(imagePathShenchanxuke)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathShenchanxuke", imagePathShenchanxuke);
        }
        if (!TextUtils.isEmpty(imagePathYingyezhizhao)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathYingyezhizhao", imagePathYingyezhizhao);
        }
    }

    @Override
    public void recoverData() {
        super.recoverData();
        String data = null;
        data = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathIDCardBehand", Config.NULL);
        if (!TextUtils.isEmpty(data)) {
            imagePathIDCardBehand = data;
        }
        data = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathIDCardFront", Config.NULL);
        if (!TextUtils.isEmpty(data)) {
            imagePathIDCardFront = data;
        }
        data = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathIDCardWith", Config.NULL);
        if (!TextUtils.isEmpty(data)) {
            imagePathIDCardWith = data;
        }
        data = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathQiyedaima", Config.NULL);
        if (!TextUtils.isEmpty(data)) {
            imagePathQiyedaima = data;
        }
        data = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathShenchanxuke", Config.NULL);
        if (!TextUtils.isEmpty(data)) {
            imagePathShenchanxuke = data;
        }
        data = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathYingyezhizhao", Config.NULL);
        if (!TextUtils.isEmpty(data)) {
            imagePathYingyezhizhao = data;
        }
    }

    @Override
    public void clearData() {
        super.clearData();
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardBehand", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardFront", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardWith", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathQiyedaima", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathShenchanxuke", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathYingyezhizhao", Config.NULL);
    }


}
